package ru.compscicenter.uno.net;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.util.Enumeration;

public class UDPServer {

    public static final int PORT = 13667;
    public static final String BROADCAST_ADDRESS = "228.0.0.1";
    public static final String BROADCAST_MESSAGE = "I'm UNO server. ";
    private static final int defaultTimeLimit = 50000000;

    private MulticastSocket socket;
    private int timeLimit = 50000000;
    private static InetAddress group;

    public UDPServer() throws IOException {
        socket = new MulticastSocket(PORT);
        group = InetAddress.getByName(BROADCAST_ADDRESS);
        socket.joinGroup(group);
        socket.setReuseAddress(true);
    }


    public int getPort() {
        return PORT;
    }

    public MulticastSocket getSocket() {
        return socket;
    }

    public InetAddress getGroup() {
        return group;
    }

    public void doBroadcast(String ip, int tcpPort, String name) throws IOException, InterruptedException {
        timeLimit = defaultTimeLimit;
        long startTime = System.currentTimeMillis();
        while (System.currentTimeMillis() - startTime < timeLimit) {
            String message = BROADCAST_MESSAGE + "IP " + ip + " port " + tcpPort + " ";
            group = InetAddress.getByName(BROADCAST_ADDRESS);
            final DatagramPacket broadcastPacket = new DatagramPacket(message.getBytes(), message.length(), group, PORT);
            socket.send(broadcastPacket);
            Thread.sleep(20);
        }
    }


    public void stop() {
        timeLimit = 0;
    }

}
